//
//  LHPhotoChooseController.m
//  WXYView
//
//  Created by lehuo on 2017/1/16.
//  Copyright © 2017年 lehuo. All rights reserved.
//

#import "LHPhotoChooseController.h"
#import "PhotoGroupModel.h"
#import "PhotoAssetModel.h"
#import "LHPhotoTableCell.h"
#import "LHPhotoShowController.h"
#import "GoalData.h"
#import <AssetsLibrary/AssetsLibrary.h>
static NSString *PCell = @"cell";
@interface LHPhotoChooseController ()<UITableViewDataSource,UITableViewDelegate>
@property(nonatomic,strong)NSMutableArray <PhotoGroupModel *> *photoModels;//保存模型
@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)ALAssetsLibrary *library;
@property(nonatomic,strong)NSMutableArray <ALAssetsGroup *> *assetGroup;
@end

@implementation LHPhotoChooseController

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self initImgData];
    [self initView];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pop) name:PostData object:nil];

}

- (void)dealloc
{
    //移除观察者
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)initView
{
    self.extendedLayoutIncludesOpaqueBars = NO;
    self.edgesForExtendedLayout = UIRectEdgeBottom | UIRectEdgeLeft | UIRectEdgeRight;
    self.view.backgroundColor = [UIColor whiteColor];
    _tableView = [[UITableView alloc] initWithFrame:self.view.bounds];
    _tableView.contentInset = UIEdgeInsetsMake(20, 0, 0, 0);
    _tableView.dataSource = self;
    _tableView.delegate = self;
    [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([LHPhotoTableCell class]) bundle:nil] forCellReuseIdentifier:PCell];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
    self.title = @"选择相册";
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancelClick)];
}

#pragma mark - 获取相册图片
- (void)initImgData
{
    self.library = [[ALAssetsLibrary alloc] init];
    
    __weak typeof(self) weakSelf = self;
    
    [self.library enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop)
     {
         
         if (group)
         {
             PhotoGroupModel *photoGroupModel = [[PhotoGroupModel alloc] init];
             photoGroupModel.group = group;
             photoGroupModel.localizedTitle = [group valueForProperty:@"ALAssetsGroupPropertyName"];
             [weakSelf.photoModels addObject:photoGroupModel];
         }
     } failureBlock:nil];
    
    //延时0.1s，获取图片系统开辟了子线程需要时间
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSArray *array = [self.photoModels copy];
        for (int i = 0; i < array.count; i++)
        {
            PhotoGroupModel *model =  [array objectAtIndex:i];
            [model.group enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
                if(result){
                    PhotoAssetModel *asset = [[PhotoAssetModel alloc] init];
                    asset.asset = result;
                    [self.photoModels[i].assets addObject:asset];
                }
            }];
        }
        //首次直接进入第一个相册
        LHPhotoShowController *showVC = [[LHPhotoShowController alloc] init];
        showVC.assets = self.photoModels[0].assets;
        showVC.title = self.photoModels[0].localizedTitle;
        showVC.photoModels = self.photoModels;
        [self.navigationController pushViewController:showVC animated:NO];
    });
    
   
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.tableView reloadData];
}

- (void)cancelClick
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - TabbleView Delegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.photoModels.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LHPhotoTableCell *cell = [tableView dequeueReusableCellWithIdentifier:PCell];
    [cell setCellValue:self.photoModels[indexPath.row]];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 65;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    LHPhotoShowController *showVC = [[LHPhotoShowController alloc] init];
    showVC.assets = self.photoModels[indexPath.row].assets;
    showVC.title = self.photoModels[indexPath.row].localizedTitle;
    showVC.photoModels = self.photoModels;
    [self.navigationController pushViewController:showVC animated:YES];
}

#pragma mark - lazy loading

- (NSMutableArray<PhotoGroupModel *> *)photoModels
{
    if (!_photoModels)
    {
        _photoModels = [NSMutableArray array];
    }
    return _photoModels;
}

-(NSMutableArray<ALAssetsGroup *> *)assetGroup
{
    if (!_assetGroup)
    {
        _assetGroup = [NSMutableArray array];
    }
    return _assetGroup;
}

#pragma mark - 接到通知，销毁控制器
- (void)pop
{
    [self dismissViewControllerAnimated:NO completion:nil];
}

@end
